package com.appdupe.flamernofb;



import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.appdupe.flamer.LoginUsingFacebook;


import com.appdupe.flamer.adapter.GridEventosAdapter;
import com.appdupe.flamer.pojo.UserFaceBookInfo;
import com.appdupe.flamer.utility.AppLog;
import com.appdupe.flamer.utility.SessionManager;
import com.appdupe.flamer.utility.Ultilities;
import com.appdupe.flamerchat.db.DatabaseHandler;
import com.facebook.FacebookActivity;
import com.facebook.LoggingBehaviors;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.google.gson.Gson;
import com.google.gson.JsonArray;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

public class EventsActivity extends FacebookActivity implements OnClickListener {
	private Button btnClose;
	private SessionManager manager;
	private BackGroundTaskgettingEvents bgtfb;
	private UserFaceBookInfo mUserFaceBookInfo;
	private SharedPreferences preferences;
	private Session session;
	private Session.StatusCallback statusCallback = new SessionStatusCallback(this);
	private GridView grid;
	
	private class SessionStatusCallback implements Session.StatusCallback {
		private Context c;
		public SessionStatusCallback(Context c){
			this.c = c;
		}
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			Log.e("TAG", "Status Call Back from fb, session : " + session
					+ " state : " + state);
			updateView();
		}
		private void updateView() {

			Session session = Session.getActiveSession();
			if (session.isOpened()) {
				Log.e("TAG", "Session open : " + session);
				
				//passa referencia para preencher no background
				new BackGroundTaskgettingEvents(c).execute();

			} else {
				/*buttonLoginLogout.setOnClickListener(new OnClickListener() {
					public void onClick(View view) {
						
						Log.e(TAG, "this clicked.");
						onClickLogin();

					}
				});
				loginwithfacebook.setOnClickListener(new OnClickListener() {
					public void onClick(View view) {
						onClickLogin();
					}
				});*/
			}
		}
	}

	
	public SessionManager getManager(){
		return manager;
		
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_events);
		
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		
		Settings.addLoggingBehavior(LoggingBehaviors.INCLUDE_ACCESS_TOKENS);
		/*restore session*/
		Session session = Session.getActiveSession();
		if (session == null) {
			if (savedInstanceState != null) {
				session = Session.restoreSession(this, null, statusCallback,
						savedInstanceState);
			}
			// still null then create new session
			if (session == null) {
				session = new Session(this);
			}

			Session.setActiveSession(session);
			AppLog.Log("TAG",
					"onCreate savedInstanceState state " + session.getState());

			if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
				AppLog.Log("TAG", "ACCEESS TOKEN Loaded");
			}
		}
		
		
		btnClose = (Button) findViewById(R.id.btnEventsClose);
		btnClose.setOnClickListener((OnClickListener) this);
		bgtfb = new BackGroundTaskgettingEvents(this);
		
		bgtfb.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.events, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.btnEventsClose:
			onBackPressed();
			break;
		// Change By Dilavar
		// case R.id.ivQuestionIndicatorLeft:
		// pager.setCurrentItem(pager.getCurrentItem() - 1);
		// break;
		// case R.id.ivQuestionIndicatorRight:
		// pager.setCurrentItem(pager.getCurrentItem() + 1);
		// break;
		default:
			break;
		}
	}
	
	
	
	private class BackGroundTaskgettingEvents extends
		AsyncTask<String, Void, Void> {
		private Context contexto;
		private JSONObject userObject ;
		private boolean flagForResponse = true;
		SessionManager manager = new SessionManager(EventsActivity.this);
		String mfacebookid = manager.getFacebookId();
	
	
	    public BackGroundTaskgettingEvents(Context c){
	    	this.contexto = c;
	    }
		
			
		private Ultilities mUltilities = new Ultilities();
		private DatabaseHandler databaseHandler = new DatabaseHandler(EventsActivity.this);
		@Override
		protected void onPostExecute(Void result)    {
			 String[ ] GRID_DATA = new String[] { 
		               "Windows" ,
		               "iOS", 
		               "Android" ,
		               "Blackberry",
		               "Java" ,
		               "JQuery", 
		               "Phonegap",
		               "SQLite",        
		               "Thread" ,
		               "Video"
		            };
			try{
	        //The task is complete, tell the status bar about it
			grid = (GridView) findViewById(R.id.gridView1);
			ArrayList list = null;
			list = new ArrayList<String>();
			//getActivity().getApplicationContext()
			JSONArray arra = this.userObject.getJSONArray("data");
			Log.i("TAG","TESTE"+arra.getJSONObject(0).get("name"));
			 //list.add("Evt:"+ arra.getJSONObject(0).get("name"));
		       
			//ArrayAdapter<String> adp = new ArrayAdapter<String>(EventsActivity.this.getApplicationContext(),android.R.layout.simple_dropdown_item_1line,list);
	        //grid.setAdapter(adp);
	        grid.setAdapter(  new GridEventosAdapter( contexto, arra ) );
	        
			}catch(JSONException e){
				Log.i("TAG", "ERROR:"+e.getMessage());
			}
	    }
		
		@Override
		protected Void doInBackground(String... params) {
			try {
				
				Settings.addLoggingBehavior(LoggingBehaviors.INCLUDE_ACCESS_TOKENS);
				
				Session mCurrentSession = Session.getActiveSession();
				
				Log.i("TAG","token: "+mCurrentSession.getAccessToken());
				String URL = "https://graph.facebook.com/me/events?access_token="+ mCurrentSession.getAccessToken();
				Log.i("TAG","url "+URL);
			HttpClient hc = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL);
			HttpResponse rp = hc.execute(get);
			Log.i("TAG","rqcode"+ rp.getStatusLine().getStatusCode());
			
			
			
			
			
			if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String queryAlbums = EntityUtils.toString(rp.getEntity());
				
				AppLog.Log("TAG","BackGroundTaskForFetchingDataFromFaceBook   doInBackground fetch all user data Step 1 : "
							+ queryAlbums);
			Gson gson = new Gson();
			Log.i("TAG","OBK:"+ queryAlbums);
			this.userObject = new JSONObject(queryAlbums);
			//mUserFaceBookInfo = gson.fromJson(queryAlbums,
			//		UserFaceBookInfo.class);

		}
		//	Toast.makeText("TAG", "@@@@", 131331);
		
			
		databaseHandler.deleteUserData();
		databaseHandler.deleteMatchedlist();
		manager.logoutUser();

	} catch (Exception e) {
		
		Log.i("TAG", "FLAG RESPONSE CATCH:" + flagForResponse);
		
		e.printStackTrace();
		flagForResponse = false;
		// logDebug("BackGroundTaskForFetchingDataFromFaceBook   doInBackground exception "+
		// e);
		return null;
	} catch (Throwable e) {
		
		Log.i("TAG", "FLAG RESPONSE CATCH:" + flagForResponse);
		e.printStackTrace();
		flagForResponse = false;
	}
	return null;
	}
	}
}